package com.xiaolei.openokjoke.Fragments

import android.graphics.Color
import android.os.Message
import android.support.v7.widget.LinearLayoutManager
import com.umeng.analytics.MobclickAgent
import com.xiaolei.openokjoke.Adapters.JokeAdapter
import com.xiaolei.openokjoke.Base.BaseV4Fragment
import com.xiaolei.openokjoke.Beans.JokeBean
import com.xiaolei.openokjoke.Configs.EventAction
import com.xiaolei.openokjoke.Exts.enqueue
import com.xiaolei.openokjoke.Net.APPNet
import com.xiaolei.openokjoke.Net.BaseRetrofit
import com.xiaolei.openokjoke.R
import kotlinx.android.synthetic.main.fragment_txtjoke.*
import java.util.*

/**
 * 文本笑话
 * Created by xiaolei on 2018/3/8.
 */
class TxtJokeFragment : BaseV4Fragment()
{
    private val appnet by lazy {
        BaseRetrofit.create(APPNet::class.java)
    }
    private val list = LinkedList<JokeBean>()
    private val adapter by lazy {
        JokeAdapter(list, activity)
    }
    override fun contentViewId(): Int = R.layout.fragment_txtjoke

    override fun initObj()
    {

    }

    override fun initView()
    {
        refresh_layout.setColorSchemeColors(Color.parseColor("#ecc96a"))
        refresh_layout.setOnRefreshListener {
            loadServerData()
        }
    }

    override fun initData()
    {

    }

    override fun setListener()
    {
        recycleview.layoutManager = LinearLayoutManager(activity).apply {
            orientation = LinearLayoutManager.VERTICAL
        }
        recycleview.adapter = adapter
    }

    override fun loadData()
    {
        loadServerData(true)
    }

    private fun loadServerData(cache: Boolean = false)
    {
        context?.let {
            val call = if (cache)
            {
                appnet.cacheJoke(JokeBean.Type.txt)
            } else
            {
                appnet.joke(JokeBean.Type.txt)
            }
            call.enqueue(it, { result ->
                result.content?.let {
                    list.addAll(0, it)
                }
            }, {
                adapter.notifyDataSetChanged()
                refresh_layout.isRefreshing = false
                MobclickAgent.onEvent(activity, "refresh_txt")
            }, {})
        }
    }

    override fun onEvent(msg: Message)
    {
        if (msg.what == EventAction.refreshTxt)
        {
            val layoutManager = recycleview.layoutManager as LinearLayoutManager
            val firstPosition = layoutManager.findFirstVisibleItemPosition()
            if(firstPosition == 0) // 显示第一个
            {
                refresh_layout.isRefreshing = true
                loadServerData(false)
            }else // 滚回最顶部
            {
                recycleview.smoothScrollToPosition(0)
            }
        }
    }
}